<?php

namespace App\Admin\Controllers;

use App\Models\AdminsModel;
use App\Services\SessionService;
use Illuminate\Support\Facades\Hash;
use Lib\Util\JWT;

class LoginController extends Controller
{
    protected $check_login = false;

    /**
     * 登陆
     * @return bool
     */
    public function login()
    {
        $username = $this->request->input('username');
        $password = $this->request->input('password');
        $key = $this->request->input('key');
        $code = $this->request->input('code');

        if (empty($username) || empty($password) || empty($code)) {
            return $this->fail(CODE_ERR_PARAM);
        }

        if (!captcha_api_check($code, $key)) {
            return $this->fail(CODE_ERR_AUTH_VERIFICATION_CODE);
        }

        $admin = AdminsModel::query()->where(['username' => $username])->first();

        if (empty($admin)) {
            return $this->fail(CODE_ERR_AUTH_USERNAME);
        }

        if (!Hash::check($password, $admin->password)) {
            return $this->fail(CODE_ERR_AUTH_PASSWORD);
        }

        $data = [
            'iat' => time(),
            'exp' => strtotime('+1 day'),
            'admin_info' => [
                'id' => $admin->id,
                'username' => $admin->username,
                'role_id' => $admin->role_id,
                'is_admin' => $admin->is_admin
            ]
        ];

        $token = JWT::token($data);

        SessionService::getInstance()->set(md5($token), 1, 'EX', 86400);

        return $this->success([
            'uuid' => $admin->id,
            'username' => $admin->username,
            'token' => $token,
        ]);
    }

    public function logout()
    {
        $token = $this->request->input('token');

        SessionService::getInstance()->del(md5($token));
        return $this->success();
    }
}
